package com.averroes
{	
	public class Statistics
	{
		/**
		 * Calculates the arithmetic mean
		 * @param array
		 * @return 
		 * 
		 */		
		public static function mean(array:Array):Number
		{
			return sum(array)/array.length;
		}
		
		/**
		 * Calculates the sum of items in an array.
		 * @param array
		 * @return 
		 * 
		 */		
		public static function sum(array:Array):Number
		{
			var ret:Number =0;
			for each (var i:Number in array)
				ret += i;
			return ret;
		}
		
		/**
		 * Calculates the standard deviation of an array of numbers. The formula is (LaTeX):
		 * <math> \sigma = \sqrt{\frac{1}{N} \sum_{i=1}^N (x_i - \overline{x})^2}. </math>
		 * @param array
		 * @return 
		 * 
		 */		
		public static function std(array:Array):Number
		{
			var mean:Number = mean(array);
			
			var variance:Number = 0;
			for (var i:int=0; i<array.length; i++)
				variance += (array[i] - mean)*(array[i] - mean)/array.length;
				
			//standard deviation is the square root of variance
			return Math.sqrt(variance);
		}
		
		/**
		 * Calculates the central moving average of an array
		 * @return 
		 * 
		 */		
		public static function movingAverages(array:Array, center:int):Array
		{
			var ret:Array;
			//todo: calculate moving average
			return ret;
		}
		/**
		 * The slope is <math>m = \dfrac{n\sum{xy} - \sum{x}\sum{y}}{n\sum{x^2}-(\sum{x})^2}</math>
		 * The intercept is <math>b=\dfrac{\sum{y}-m\sum{x}}{n}</math>
		 * @param Y
		 * @param X
		 * @return 
		 * 
		 */		
		public static function regress(Y:Array, X:Array):Object
		{
			var sumx:Number = 0;
			var sumy:Number = 0; 
			var sumxy:Number = 0; 
			var sumxx:Number = 0;
			for (var i:int=0; i<X.length; i++)
			{
				sumx += X[i];				
				sumy += Y[i];
				sumxy += X[i]*Y[i];
				sumxx +=X[i]*X[i];
			}
			
			var n:int = X.length;
			var d:Number = n*sumxx - (sumx*sumx);
			var m:Number = 0;
			if (d > 0)
				m = (n*sumxy - sumx*sumy)/(n*sumxx - (sumx*sumx));
			var b:Number = (sumy - m*sumx)/n;
			return {m: m, b: b };
		}	
	}
}